const ffi = require("ffi-napi");
const path = require("path");
const log = require("electron-log");

exports.useSdk = function useSdk() {
  try {
    // 定义 DLL 文件中的函数类型和参数类型
    // eslint-disable-next-line no-undef
    let dllPPCS_APIPath = path.join(__static, "sdk", "libHCTP.dll");
    // eslint-disable-next-line no-undef
    // let dllcygHCTPPath = path.join(__static, "sdk", "cygHCTP.dll");

    if (process.env.NODE_ENV !== "development") {
      // dllcygHCTPPath = path.join(
      //   process.resourcesPath,
      //   "app.asar.unpacked",
      //   "sdk",
      //   "cygHCTP.dll"
      // );
      dllPPCS_APIPath = path.join(
        process.resourcesPath,
        "app.asar.unpacked",
        "sdk",
        "libHCTP.dll"
      );
    }

    const kernel32 = ffi.Library("kernel32", {
      SetDllDirectoryA: ["bool", ["string"]],
    });

    kernel32.SetDllDirectoryA(path.join(dllPPCS_APIPath, ".."));

    // log.info("cygHCTP.dll 路径", dllcygHCTPPath);
    log.info("PPCS_API.dll 路径", dllPPCS_APIPath);

    // const dllPPCS_API = ffi.Library(dllPPCS_APIPath, {});

    const libPPCS = ffi.Library(dllPPCS_APIPath, {
      hctpGetVersion: ["string", []],
      // PPCS_GetAPIVersion: ["uint32", []],
      // PPCS_GetAPIInformation: ["string", []],
      // PPCS_QueryDID: ["int32", ["string", "string", "int32"]],
      // PPCS_Initialize: ["int32", ["string"]],
      // PPCS_DeInitialize: ["int32", []],
      // PPCS_NetworkDetect: ["int32", ["pointer", "uint16"]],
      // PPCS_NetworkDetectByServer: ["int32", ["pointer", "uint16", "string"]],
      // PPCS_Share_Bandwidth: ["int32", ["char"]],
      // PPCS_Enable_SmartDevice: ["int32", ["char"]],
      // PPCS_Listen: ["int32", ["string", "uint32", "uint16", "char", "string"]],
      // PPCS_Listen_Break: ["int32", []],
      // PPCS_LoginStatus_Check: ["int32", ["pointer"]],
      // PPCS_Connect: ["int32", ["string", "char", "uint16"]],
      // PPCS_ConnectByServer: ["int32", ["string", "char", "uint16", "string"]],
      // PPCS_Connect_Break: ["int32", []],
      // PPCS_Check: ["int32", ["int32", "pointer"]],
      // PPCS_Close: ["int32", ["int32"]],
      // PPCS_ForceClose: ["int32", ["int32"]],
      // PPCS_Write: ["int32", ["int32", "uchar", "string", "int32"]],
      // PPCS_Read: ["int32", ["int32", "uchar", "string", "pointer", "uint32"]],
      // PPCS_Check_Buffer: ["int32", ["int32", "uchar", "pointer", "pointer"]],
      // PPCS_PktSend: ["int32", ["int32", "uchar", "string", "int32"]],
      // PPCS_PktRecv: [
      //   "int32",
      //   ["int32", "uchar", "string", "pointer", "uint32"],
      // ],
    });

    log.info("dllPPCS_API.dll 加载成功", libPPCS.hctpGetVersion());

    // const dllcygHCTP = ffi.Library(dllcygHCTPPath, {
    //   hctpGetVersion: ["string", []],
    // });

    return libPPCS.hctpGetVersion();
  } catch (error) {
    log.error("cygHCTP.dll 或者 dllPPCS_API.dll 加载失败");
    log.error(error.message);
    return "error";
  }
};
